package com.tajlip;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * A Filter that abstracts the Java code required for showing the current comic.
 * This relies on the ShowImageFilter to send back images as 'image/png' data
 * when a user's browser requests them.
 */
public class CurrentComicFilter implements Filter {

    private FilterConfig filterConfig = null;
    
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        // the comic to show (optional)
        Integer id = null;
        if (req.getRequestURI().contains("/comic/")) {
            try {
                id = Integer.parseInt(req.getRequestURI().split("/comic/|\\.html")[1]);
            } catch (Exception e) {
                // noop
            }
        }

        // snag an isntance of Google's database
        DatastoreService dataService = DatastoreServiceFactory.getDatastoreService();

        // query all the comies from BigTable
        Query query = new Query(Comic.KIND);
//        query.addSort("timestamp", SortDirection.DESCENDING);
        if (id != null) {
            query.addFilter("id", Query.FilterOperator.EQUAL, id);
        }
        PreparedQuery preparedQuery = dataService.prepare(query);
        Entity result = preparedQuery.asSingleEntity();
        Comic comic = new Comic();
        comic.id = ((Long) result.getProperty("id")).intValue();
        comic.title = (String) result.getProperty("title");
        comic.description = (String) result.getProperty("description");
        comic.tags = (String) result.getProperty("tags");
        comic.timestamp = (Long) result.getProperty("timestamp");
        // don't need these. binary data isn't used here
//        comic.image = (Blob) result.getProperty("image");
//        comic.imageSmall = (Blob) result.getProperty("image-small");

        // put in request scope
        request.setAttribute("comic", comic);

        // put next -- watch for last entry
        request.setAttribute("next", comic.id + 1);

        // put previous -- watch for last entry
        request.setAttribute("previous", comic.id - 1);

        // put the current id
        request.setAttribute("current", id);


        // always send to filter-test.jsp
        req.getRequestDispatcher("/show.jsp").forward(req, res);
    }

    public void destroy() {
    }

    public void init(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }
}
